import json
from plistlib import InvalidFileException
from zipfile import BadZipfile
from django import forms
from django.db.models import Q
from django.shortcuts import render
from django.http import HttpResponse, request, HttpResponseBadRequest, JsonResponse
from django.views.decorators.csrf import csrf_exempt

from app01 import models
import logging
from openpyxl import load_workbook
from django.shortcuts import redirect
import os
import pandas as pd
from django.http import HttpResponse, HttpResponseBadRequest
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from django.shortcuts import redirect

from app01.models import EquipmentRoomInfo
from app01.pagination import Pagination

logger = logging.getLogger(__name__)


class BootStrapModelForm(forms.ModelForm):
    """
    该类用于生成带有Bootstrap样式的ModelForm。
    它会自动为每个字段的Widget添加Bootstrap样式类和其他属性。
    """

    def __init__(self, *args, **kwargs):
        """
        初始化方法，用于设置ModelForm字段的Widget属性。

        参数:
        *args: 位置参数，传递给父类的初始化方法。
        **kwargs: 关键字参数，传递给父类的初始化方法。
        """
        super().__init__(*args, **kwargs)
        # 循环ModelForm中的所有字段，给每个字段的插件设置
        for name, field in self.fields.items():
            # 字段中有属性，保留原来的属性，没有属性，才增加。
            if field.widget.attrs:
                field.widget.attrs["class"] = "form-control"
                field.widget.attrs["placeholder"] = field.label
            else:
                field.widget.attrs = {
                    "class": "form-control",
                    "placeholder": field.label
                }


# Create your views here.
class MyForm(BootStrapModelForm):
    # 定义表单类，继承自BootStrapModelForm，用于用户信息的展示和编辑
    # user_search = forms.CharField(
    #     label='用户负责人',
    #     widget=forms.TextInput(attrs={'placeholder': '搜索用户负责人'})
    # )
    class Meta:
        # 指定模型来源和表单中包含的字段
        model = models.EquipmentRoomInfo
        # 选择用户信息模型中的特定字段以包含在此表单中
        fields = ['Core_EquipmentRoom', 'floor_room', 'EquipmentRoom_type', 'EquipmentRoom_user_info', 'description']


def EquipmentRoom_add(request):
    try:
        # 验证请求方法是否为 GET 或 POST
        if request.method not in ["GET", "POST"]:
            return HttpResponseBadRequest("Invalid request method")

        if request.method == "GET":
            # 创建空表单实例
            form = MyForm()
            # 返回渲染后的页面
            return render(request, 'EquipmentRoom_info/EquipmentRoom_add.html', {"form": form})

        elif request.method == "POST":
            # 使用 POST 数据创建表单实例
            form = MyForm(request.POST)

            # 验证表单数据
            if form.is_valid():
                # 保存数据到数据库
                form.save()
                # 返回成功响应
                return redirect("EquipmentRoom_info/EquipmentRoom_list.html")

            else:
                # 表单数据无效时返回错误响应
                logger.error(f"Invalid form data: {form.errors}")
                return HttpResponseBadRequest("表单数据无效")

    except Exception as e:
        # 记录详细的错误日志
        logger.error(f"An error occurred: {e}")
        return HttpResponseBadRequest("An error occurred while processing the request.")


def EquipmentRoom_list(request):
    """
    获取用户信息并渲染部门列表页面。

    本函数查询所有用户信息对象，并将其传递给部门列表模板进行渲染。
    主要用于展示各部门的信息，并允许对这些部门信息进行操作，如查看、编辑、删除等。

    参数:
    - request: HTTP请求对象，包含了请求的元数据和请求内容。

    返回:
    - render: 渲染后的HTML页面，包含部门列表信息。
    """
    try:
        # 查询用户信息对象
        values = request.GET.get('values', '')
        print(values)
        if values:
            # 使用 Q 对象进行跨字段模糊搜索
            queryset = models.EquipmentRoomInfo.objects.filter(
                Q(Core_EquipmentRoom__icontains=values) |
                Q(floor_room__icontains=values) |
                Q(EquipmentRoom_type__icontains=values) |
                Q(EquipmentRoom_user_info__icontains=values)

            )
            # 添加其他你想搜索的字段
        else:
            queryset = models.EquipmentRoomInfo.objects.all()
        page_object = Pagination(request, queryset)

        context = {
            "values": values,
            "queryset": page_object.page_queryset,  # 分完页的数据
            "page_string": page_object.html()  # 页码
        }
        # 渲染部门列表页面，并将查询到的用户信息对象传递给模板
        return render(request, 'EquipmentRoom_info/EquipmentRoom_list.html', context)


    except Exception as e:
        logger.error(f"Error occurred while fetching user info: {e}")
        return HttpResponseBadRequest("获取用户信息时发生错误")


@csrf_exempt
def search_users(request):
    if request.method == 'POST':
        try:
            # 解析 JSON 数据
            data = json.loads(request.body)
            query = data.get('keyword', '')
            print(f'查询内容: {query}')

            if query:
                users = models.User_info.objects.filter(
                    Q(username__icontains=query) | Q(department__icontains=query)
                )
                results = [{'username': user.username,
                            'department': user.department,
                            'group': user.group,
                            'phone_number': user.phone_number,
                            'description': user.description} for user in users]
                return JsonResponse(results, safe=False)

        except json.JSONDecodeError:
            return JsonResponse({'error': 'Invalid JSON'}, status=400)

    return JsonResponse([], safe=False)


# @csrf_exempt
# def search_users(request):
#     print(request.POST)
#     print(request.POST.get('q'))
#     print('调用我了没')
#     query = request.GET.get('q', '')
#     if query:
#         users = models.User_info.objects.filter(
#             Q(username__icontains=query) | Q(department__icontains=query)  # 这里假设可以根据username或department模糊查询
#         )
#         results = [{'username': user.username, 'department': user.department} for user in users]
#         return JsonResponse(results, safe=False)
#     return JsonResponse([], safe=False)


@csrf_exempt
def add_equipment_room(request):
    if request.method == 'POST':
        try:
            # 解析 JSON 数据
            data = json.loads(request.body)

            # 从请求数据中提取字段
            core_equipment_room = data.get('Core_EquipmentRoom')
            floor_room = data.get('floor_room')
            equipment_room_type = data.get('EquipmentRoom_type')
            equipment_room_user_info = data.get('EquipmentRoom_user_info')
            description = data.get('description', '')

            # 创建新的设备机房信息实例
            equipment_room = EquipmentRoomInfo(
                Core_EquipmentRoom=core_equipment_room,
                floor_room=floor_room,
                EquipmentRoom_type=equipment_room_type,
                EquipmentRoom_user_info=equipment_room_user_info,
                description=description
            )
            equipment_room.save()  # 保存到数据库

            # 成功返回 200 状态码
            return JsonResponse({'message': '设备机房信息添加成功'}, status=200)

        except json.JSONDecodeError:
            # 解析 JSON 失败，返回 500 状态码
            return JsonResponse({'error': 'Invalid JSON'}, status=500)
        except Exception as e:
            # 其他异常，返回 500 状态码
            return JsonResponse({'error': str(e)}, status=500)

    # 如果请求方法不是 POST，返回 405 状态码
    return JsonResponse({'error': 'Invalid request method'}, status=405)
